/**
 * 该插件为表单插件
 */
(function ($) {
    var toObjectMap = {
        "": "input",
        "text": "input",
        "textarea": "textArea",
        "dropdown": "dropdown"
    };
    var controlList = new Array();
    $.mrdForm = $.mrdForm || {};
    $.extend($.mrdForm, {
        formContainerId: null,
        formId: null,
        allCoulumns: null,
        formDefaultData: null,
        mrdFormSettings: {},
        defaultSettings: {
            'title': "",// 表单标题
            'module': 'query',// 表单模式 分成查询模式(query)和保存模式(save)
            'numCount': 3,// 每行多少个控件
            'columnNum': 6,// 暂时无用
            'width': "100%",// 表格宽度
            'height': '30',// 一行的高度
            'lwidth': '100',// label的默认宽度
            'cwidth': '250',// 输入框的默认宽度
            'lalign': "right",// label的默认水平位置(居左，居右，居中)
            'lvalign': "middle",// label的默认垂直位置(居上，居下，居中)
            'calign': "left",// 输入框的默认水平位置(居左，居右，居中)
            'cvalign': "middle",// 输入框的默认垂直位置(居上，居下，居中)
            'fieldsets': [],// 数据组合框
            'columns': [],// 字段配置
            'buttons': {},// 按钮配置
            'grid': {},// jqgrid配置
            'form': {}
            // 表单配置
        },
        columnDefaultSettings: {
            'classId': "",
            'name': "",// 输入框id/name
            'label': "",// label名称
            'type': "text",// 输入框类型(text,textarea,dropdown,date)
            'value': "",// 默认值
            'colspan': "",// 输入框占据的空间
            'operator': "cn",// 查询操作符(已废弃)
            'op': "cn",// 查询操作符
            'height': null,// 高度
            'cwidth': null,// 输入框的宽度
            'lwidth': null,// label的宽度
            'lalign': null,// label的水平位置
            'lvalign': null,// label的垂直位置
            'calgin': null,// 输入框的水平位置
            'cvalign': null,// 输入框的垂直位置
            'hidden': false, // 设置隐藏
            'readonly': false,// 设置只读
            'validate': null
            // 表单验证,validationEngine表单验证参数
        },
        /**
         * 查询模式按钮组
         */
        buttonsDefaultSettingsForQuery: {
            'position': 'right',
            'query': true,// 是否显示查询按钮
            'reset': true,// 是否显示重置按钮
            'queryEvent': null,// 重写查询点击事件
            // 'resetEvent' : null,// 重写重置点击事件，不在允许重写重置按钮
            'order': 'queryButton,resetButton',// 查询和重置的排序,暂时未启用
            'custom': []
            // 自定义按钮，内容为按钮对象，具体参考buttonQuery
        },
        /**
         * 保存模式按钮组
         */
        buttonsDefaultSettingsForSave: {
            'position': 'center',
            'save': true,// 是否显示查询按钮
            'reset': true,// 是否显示重置按钮
            'saveEvent': null,// 重写查询点击事件
            'order': 'saveButton,resetButton',// 查询和重置的排序,暂时未启用
            'custom': []
            // 自定义按钮，内容为按钮对象，具体参考buttonQuery
        },
        /**
         * 查询按钮
         */
        buttonQuery: {
            'id': 'queryButton', // 按钮id
            'disabled': false,// 是否禁用
            'value': "查询",// 按钮显示名称
            /**
             * 按钮点击事件
             */
            'click': function () {
                var gridSelect = "#" + $.mrdForm.mrdFormSettings.grid.id;
                var filters = $.mrdForm.filterString();
                // 如果没有查询条件，则返回
                if (!$.mrdForm.isEmpty(filters)) {
                    var postData = $(gridSelect).jqGrid("getGridParam",
                        "postData");// 获取将要提交的数据
                    $.extend(postData, {
                        filters: filters
                    });// 将filters插入将要提交的数据
                }
                $(gridSelect).jqGrid("setGridParam", {
                    search: true
                    // 将jqGrid的search选项设为true
                }).trigger("reloadGrid", [{
                    page: 1
                }]); // 重新载入Grid表格
            }
        },
        /**
         * 获取form的jqgrid的filter的字符串组合
         */
        filterString: function () {
            // var gridSelect = "#" + $.mrdForm.mrdFormSettings.grid.id;
            var rules = "";// 定义rules
            var columns = this.mrdFormSettings.columns;// 获取表格配置
            $.each(
                $("#" + $.mrdForm.formContainerId
                    + " td[id^='td_control_']"), function (i, n) {
                    var control = $(n).children().first();
                    if (!$.mrdForm.isEmpty(control.val())) {
                        var fieldName = control.attr('name');
                        var op = "";
                        $.each(columns, function (j, m) {
                            if (m.name == fieldName) {
                                op = m.op;
                            }
                        });
                        if (op == null || op == "") {
                            op = "cn";
                        }
                        rules += "{'field':'" + fieldName + "','op':'" + op
                            + "','data':'" + control.val() + "'},";// 组装rules
                    }
                });// 如果没有查询条件，则返回
            if (!$.mrdForm.isEmpty(rules)) {
                rules = rules.substring(0, rules.length - 1);
                var filters = '{"groupOp":"AND","rules":[' + rules + ']}';// 定义filters
                return filters;
            } else {
                return "";
            }
        },
        /**
         * 获取form内容的对象
         */
        filterObject: function (objectst) {
            // var gridSelect = "#" + $.mrdForm.mrdFormSettings.grid.id;
            var st = "return ";
            var data = "";
            if (objectst) {
                objectst += ".";
            } else {
                objectst = "";
            }
            $.each(
                $("#" + $.mrdForm.formContainerId
                    + " td[id^='td_control_']"), function (i, n) {
                    var control = $(n).children().first();
                    if (!$.mrdForm.isEmpty(control.val())) {
                        data += "'" + objectst + control.attr('name')
                            + "':'" + control.val() + "',";// 组装rules
                    }
                });// 如果没有查询条件，则返回
            if (data) {
                data = data.substring(0, data.length - 1);
                st = st.concat("{", data, "}");
            } else {
                st = st.concat("{}");
            }
            return (new Function(st))();
        },
        /**
         * 保存按钮
         */
        buttonSave: {
            'id': 'saveButton', // 按钮id
            'disabled': false,// 是否禁用
            'value': "保存",// 按钮显示名称
            'click': function () {
                $("#" + $.mrdForm.formId).submit();
            }
        },
        /**
         * 重置按钮
         */
        buttonReset: {
            'id': 'reset',
            'disabled': false,
            'type': 'reset',
            'value': "重置"
        },
        /**
         * jqgrid的默认配置
         */
        defaultGridSettings: {
            id: null,// 表格编号
            url: null,// ajax读取数据的链接
            datatype: "json",// 数据类型
            autowidth: true,// 自动计算宽度
            width: "100%", // 宽度
            height: '100%',// 高度
            scrollOffset: 20,// 浏览器滚动条宽度
            colNames: [],// 标题及排序
            colModel: null,// 字段定义
            mtype: "post",// 提交方式
            multiselect: false,// 是否允许多选
            caption: null,// 标题
            viewrecords: true,// 是否显示数据页数信息
            rowNum: 15,// 分页数
            rowList: [15, 30, 50],// 在pagebar中的可选择分页数大小
            sortname: null,// 排序字段
            prmNames: null,// 分页配置
            jsonReader: {
                // 从哪个json对象中取值
                root: null,
                // 当前页字段名
                page: "page.currentPage",
                // 总页数字段名
                total: "page.totlePage",
                // 总记录数字段名
                records: "page.totle",
                // 指明每行的数据是可以重复的，如果设为false，则会从返回的数据中按名字来搜索元素，这个名字就是colModel中的名字
                repeatitems: false
            },
            pager: "#pager",// 分页下标
            pagerpos: "center",// 分页的位置
            // 加载数据失败
            loadError: function (xhr, status, error) {
                var type = xhr.getResponseHeader("Content-Type");
                if (type == "text/javascript") {
                    eval(xhr.responseText);
                }
            }
        },
        /**
         * 分页相关配置
         */
        defaultPage_parNames: {
            page: "pageNo", // 表示请求页码的参数名称
            rows: "size", // 表示请求行数的参数名称
            sort: "sidx", // 表示用于排序的列名的参数名称
            order: "sord" // 表示采用的排序方式的参数名称
            // search:"_search", // 表示是否是搜索请求的参数名称
            // nd:"nd", // 表示已经发送请求的次数的参数名称
            // id:"id", // 表示当在编辑数据模块中发送数据时，使用的id的名称
            // oper:"oper", // operation参数名称（我暂时还没用到）
            // editoper:"edit", // 当在edit模式中提交数据时，操作的名称
            // addoper:"add", // 当在add模式中提交数据时，操作的名称
            // deloper:"del", // 当在delete模式中提交数据时，操作的名称
            // subgridid:"id", // 当点击以载入数据到子表时，传递的数据名称
            // npage: null,
            // totalrows:"totalrows" //
            // 表示需从Server得到总共多少行数据的参数名称，参见jqGrid选项中的rowTotal
        },
        /**
         * 按钮的css
         */
        buttonBaseCss: {
            "font-size": "80%",
            "margin": "3px"
        },
        defaultFormSettings: {
            url: null,
            data: null,
            validate: null,
            ajaxForm: null,
            afterAjaxSuccess: null
        },
        /**
         * 表单验证的配置
         */
        defaultvalidateSettings: {
            validateType: 'attach',
            options: {
                // 消息位置
                promptPosition: "bottomRight",
                scroll: false
            }
        },
        /**
         * ajaxForm设置
         */
        defaultAjaxFormSettings: {
            // 提交方式
            type: "POST",
            // 提交数据格式
            dataType: "json",
            // 在提交之前做的操作
            beforeSubmit: function () {
                // 进行表达验证,
                return $("#" + $.mrdForm.formId).validationEngine("validate");
            },
            // 成功后做的操作
            success: function (responseText, statusText, xhr, $form) {
                var msg = $.parseJSON(responseText.msg).msg;
                if (msg) {
                    jw.alert(msg, {
                        onOk: function () {
                            var after = $.mrdForm.mrdFormSettings.form.afterAjaxSuccess;
                            if (after) {
                                after.call(this, responseText, statusText, xhr,
                                    $form);
                            }
                        }
                    });
                    /**
                     * var dialog = $("<div>", { 'id' :
					 * "submit-dialog-message", 'title' : '消息窗口' }).append("
                     * <p>" + msg + "
                     * </p>
                     * "); dialog.appendTo("body");
                     * $("#submit-dialog-message").dialog({ modal : true, close :
					 * function() { var after =
					 * $.mrdForm.mrdFormSettings.form.afterAjaxSuccess; if
					 * (after) { after.call(this, responseText, statusText, xhr,
					 * $form); } }, buttons : [{ 'text' : "确定", 'click' :
					 * function() { $(this).dialog("close"); dialog.remove();
					 * $(this).dialog("destroy"); } }]
					 * }).parent().css($.mrdForm.buttonBaseCss);
                     */
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus == "parsererror") {
                    var type = XMLHttpRequest.getResponseHeader("Content-Type");
                    if (this.dataType == "json" && type == "text/javascript") {
                        eval(XMLHttpRequest.responseText);
                    }
                }
            }
        },
        _initSetting: function (options) {
            var settings = this.mrdFormSettings;
            // 加载form设置
            $.extend(settings, this.defaultSettings, options);
            // 初始化输入框配置
            settings.columns = this._initColumns(settings.columns);
            // 初始化字段框
            settings.fieldsets = this._initFieldSets(settings.fieldsets,
                settings);
            // 初始化按钮组
            if (settings.module == 'save') {
                settings.buttons = $.extend({},
                    this.buttonsDefaultSettingsForSave, settings.buttons);
            } else {
                settings.buttons = $.extend({},
                    this.buttonsDefaultSettingsForQuery, settings.buttons);
            }
            // 初始化表格
            if (!this.isEmpty(settings.grid.id)) {
                if (this.isEmpty(settings.grid.colModel)) {
                    $.error("表格配置的字段信息配置不能为空!");
                    return;
                }
                settings.grid = $.extend(true, {}, this.defaultGridSettings,
                    settings.grid);
                settings.grid.prmNames = $.extend({},
                    this.defaultPage_parNames, settings.grid.prmNames);
                settings.grid.caption = settings.grid.title;
            }
            // 初始化表单设置
            if (settings.module == 'save') {
                settings.form = $.extend({}, this.defaultFormSettings,
                    settings.form);
                // 初始化表单验证配置
                settings.form.validate = $.extend({},
                    this.defaultvalidateSettings, settings.form.validate);
                // 初始化ajax提交配置
                settings.form.ajaxForm = $.extend({},
                    this.defaultAjaxFormSettings, settings.form.ajaxForm);
            }
            return settings;
        },
        /**
         * 初始化字段框，主要初始化字段
         */
        _initFieldSets: function (fieldsets, settings) {
            if (fieldsets != null && fieldsets.length != 0) {
                $.each(fieldsets, function (i, n) {
                    n.columns = $.mrdForm._initColumns(n.columns);
                    if (n.numCount == undefined || n.numCount == null) {
                        n.numCount = settings.numCount;
                    }
                    if (n.columnNum == undefined || n.columnNum == null) {
                        n.columnNum = settings.columnNum;
                    }
                });
                return fieldsets;
            } else {
                return null;
            }
        },
        /**
         * 初始化输入框配置
         */
        _initColumns: function (columns) {
            var tmp = $.map(columns, function (n) {
                var setting = {};
                $.extend(setting, $.mrdForm.columnDefaultSettings, n);
                switch (setting.type) {
                    case "textarea" :
                        setting = $.mrdForm
                            ._setTextareaSetting(setting);
                        break;
                    case "dropdown" :
                        setting = $.mrdForm
                            ._setDropDownSetting(setting);
                        break;
                    case "date" :
                        setting = $.mrdForm._setDateSetting(setting);
                        break;
                    case "munliselect" :
                        setting = $.mrdForm
                            ._setMunliSelectSetting(setting);
                        break;
                    default :
                        break;
                }
                return setting;
            });
            if (this.allCoulumns == null) {
                this.allCoulumns = new Array();
            }
            this.allCoulumns.concat(tmp);
            return tmp;
        },
        /**
         * 添加textarea类型配置
         */
        _setTextareaSetting: function (columnSettings) {
            var textareaDefaultSetting = {
                /** 以下为textarea类型的独有配置 */
                'rows': "3"// 当type为textarea时，行数
            };
            return $.extend(textareaDefaultSetting, columnSettings);
        },
        /**
         * 添加dropdown类型配置
         */
        _setDropDownSetting: function (columnSettings) {
            var dropdownDefaultSetting = {
                /** 以下为dropdown类型的独有配置* */
                'data': [],// 下拉框的值[[选项1名称，选项1值],[选项2名称，选项2值]....]
                'dropdownType': "",// 下拉框类型
                'dropdownValue': ""// 下拉输入框显示值
            };
            $.extend(dropdownDefaultSetting, columnSettings);
            if (dropdownDefaultSetting.dropdownType == "ajax") {
                var ajaxDropDownSetting = {
                    /** 以下为启用ajax方式独有* */
                    'dropdownType': "ajax",
                    'minLength': 2,
                    'dataType': "json",
                    'url': "",// 查询地址
                    'keyWordName': "k",// 查询参数(后台接收参数名)
                    'method': "post",// 提交方式
                    'success': function (data) {
                        return data.results;
                    }// ajax成功的回调函数，在方法体内需要将返回的数据组装成[[选项1名称，选项1值],[选项2名称，选项2值]....]这样的形式
                };
                return $.extend(ajaxDropDownSetting, dropdownDefaultSetting);
                // return
                // $.extend(dropdownDefaultSetting,ajaxDropDownSetting);
            } else {
                return dropdownDefaultSetting;
            }
        },
        _setMunliSelectSetting: function (columnSettings) {
            var dropDownSettings = this._setDropDownSetting(columnSettings);
            return dropDownSettings;
        },
        /**
         * 添加date类型配置
         */
        _setDateSetting: function (columnSettings) {
            var datePickDefaultSetting = {
                /** 以下属性为date类型的输入框特有属性 */
                format: "yy-mm-dd" // 日期格式，此处为js的日期格式，非java的日期格式
                // 特别注意
            };
            return $.extend(datePickDefaultSetting, columnSettings);
        },
        /**
         * 临时参数，用于统计当前行有多少个td
         */
        _currentColumns: 0,
        /**
         * fieldset编号累加
         */
        _fieldsetNum: 0,
        /**
         * 创建form表单函数
         */
        _createMrdForm: function (dom, settings) {
            var table = this._createTabelForm(dom, settings);
            if (settings.fieldsets != null && settings.fieldsets.leng != 0) {
                $.each(settings.fieldsets, function (i, n) {
                    var container = $("<tr>").appendTo(table);
                    container = $("<td>").appendTo(container);
                    container.attr({
                        "colspan": settings.numCount * 2
                    });
                    $.mrdForm._createTabelForm(container, n);
                });
            }
            this._addButtons(table, settings);
            if (settings.module == 'save') {
                // 初始化表单验证引擎
                $("#" + this.formId).validationEngine(
                    settings.form.validate.validateType,
                    settings.form.validate.options);
                // 将表单提交设置成ajaxForm提交
                $('#' + this.formId).submit(function () {
                    $(this).ajaxSubmit(settings.form.ajaxForm);
                    return false;
                });
            }
        },
        /**
         * 创建表单表格，或者根据fieldset创建表单
         */
        _createTabelForm: function (dom, settings) {
            var table = this._addTable(dom, settings);
            var tr;
            var maxColumnNum = settings.numCount * 2;
            var hiddenControls = new Array();
            if (settings.form.data) {
                this.formDefaultData = settings.form.data.call(this);
            }
            this._currentColumns = 0;
            $.each(settings.columns, function (i, n) {
                if (n.hidden == true || n.hidden == 'true') {
                    hiddenControls.push(n);
                } else {
                    if ((i - hiddenControls.length) == 0
                        || !($.mrdForm._currentColumns < maxColumnNum)
                        || ((maxColumnNum - $.mrdForm._currentColumns) < ($.mrdForm
                            .isEmpty(n.colspan) ? 2 : 2 * n.colspan))) {
                        table.append("<tr></tr>");
                        tr = table.find("tr").last();
                        $.mrdForm._currentColumns = 0;
                    } else {
                        tr = table.find("tr").last();
                    }
                    $.mrdForm._addLabel($.mrdForm._fieldsetNum + "" + i, tr, n,
                        settings);
                    $.mrdForm._addControl($.mrdForm._fieldsetNum + "" + i, tr,
                        n, settings);
                }
            });
            this._addHiddenControl(table, hiddenControls);
            return table;
        },
        /**
         * 创建表格主体
         */
        _addTable: function (dom, settings) {
            var fieldsetId = "mf_container" + this._fieldsetNum;
            var tableId = "mf_table" + this._fieldsetNum;
            this._fieldsetNum++;
            this.formContainerId = tableId;
            $("<fieldset>", {
                'id': fieldsetId,
                'class': 'replace-ui-jqgrid ui-widget ui-widget-content ui-corner-all mf_con'
            }).appendTo(dom);
            if (settings.title) {
                $("<div class=\"replace-ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix table_header\"><a href=\"javascript:void(0)\" class=\"replace-ui-jqgrid-titlebar-close HeaderButton tab_button\"><span class=\"ui-icon ui-icon-circle-triangle-s\"></span> </a><span class=\"replace-ui-jqgrid-title\">"
                    + settings.title + "</span></div>").appendTo("#"
                    + fieldsetId);
            }
            var tableObj = $("<table>", {
                'id': tableId,
                'class': "mrdTable",
                'width': this.nvl(settings.width, '100%')
            });
            var formObj = null;
            if (settings.module == 'save') {
                formObj = this._addForm(settings);
            } else {
                formObj = $("<form>");
            }
            formObj.appendTo("#" + fieldsetId);
            formObj.css("margin-right", "30px");
            tableObj.appendTo(formObj);
            return $("#" + tableId);
        },
        /**
         * 添加表单
         */
        _addForm: function (settings) {
            var formId = settings.form.id;
            if (this.isEmpty(formId)) {
                formId = "mf_form" + ($("form").size() + 1);
                this.formId = formId;
            }
            return $("<form>", {
                'id': formId,
                'action': settings.form.url
            });
        },
        /**
         * 创建字段的label
         */
        _addLabel: function (index, tr, columnSettings, settings) {
            var tdId = "td_label_" + index;
            $("<td>", {
                'id': tdId,
                'width': $.mrdForm.nvl(columnSettings.lwidth, settings.lwidth),
                'align': $.mrdForm.nvl(columnSettings.lalign, settings.lalign),
                'valign': $.mrdForm.nvl(columnSettings.lvalign,
                    settings.lvalign),
                'height': $.mrdForm
                    .nvl(columnSettings.height, settings.height)
            }).appendTo(tr);
            $("<label>" + columnSettings.label + "：</label>").appendTo("#"
                + tdId);
            this._currentColumns++;
        },
        /**
         * 创建输入框
         */
        _addControl: function (index, tr, columnSettings, settings) {
            var tdId = "td_control_" + index;
            $("<td>", {
                'id': tdId,
                'class': columnSettings.classId,
                'width': $.mrdForm.nvl(columnSettings.cwidth, settings.cwidth),
                'align': $.mrdForm.nvl(columnSettings.calign, settings.calign),
                'valign': $.mrdForm.nvl(columnSettings.cvalign,
                    settings.cvalign),
                'height': $.mrdForm
                    .nvl(columnSettings.height, settings.height)
            }).appendTo(tr);
            var tdObj = $("#" + tdId);
            if (columnSettings.colspan) {
                var col = new Number(columnSettings.colspan);
                tdObj.attr("colspan", col * 2 - 1);
                this._currentColumns += col * 2 - 1;
            } else {
                this._currentColumns++;
            }
            if (toObjectMap[columnSettings.type]) {
                var str = "var control=new " + toObjectMap[columnSettings.type]
                    + "(columnSettings);";
                eval(str);
                control.init(columnSettings);
                control.create(tdObj);
                controlList.push(control);
            } else {
                switch (columnSettings.type) {
                    case "textarea" :
                        $.mrdForm._addTextAreaControl(tdObj, columnSettings);
                        break;
                    case "dropdown" :
                        $.mrdForm._addDropdownControl(tdObj, columnSettings);
                        break;
                    case "date" :
                        $.mrdForm._addDateControl(tdObj, columnSettings);
                        break;
                    case "munliselect" :
                        $.mrdForm._addMunliselectControl(tdObj, columnSettings);
                        break;
                    default :
                        $.mrdForm._addBaseControl(tdObj, columnSettings);

                }
            }
        },
        /**
         * 创建按钮组
         */
        _addButtons: function (table, settings) {
            var baseButtons = new Array();
            var buttonSettings = settings.buttons;
            // 根据表单模式来添加按钮
            if (settings.module == 'save') {
                if (buttonSettings.save) {
                    var buttonSave = $.extend({}, this.buttonSave);
                    if (!this.isEmpty(buttonSettings.saveEvent)) {
                        buttonSave.click = buttonSettings.saveEvent;
                    }
                    baseButtons.push(buttonSave);
                }
            } else {
                if (buttonSettings.query) {
                    var buttonQuery = $.extend({}, this.buttonQuery);
                    if (!this.isEmpty(buttonSettings.queryEvent)) {
                        buttonQuery.click = buttonSettings.queryEvent;
                    }
                    baseButtons.push(buttonQuery);
                }
            }
            // 添加重置按钮
            if (buttonSettings.reset) {
                var buttonReset = $.extend({}, this.buttonReset);
                // 不再处理自定义重置事件
                // if (!this.isEmpty(buttonSettings.resetEvent))
                // {
                // buttonReset.click =
                // buttonSettings.resetEvent;
                // }
                baseButtons.push(buttonReset);
            }
            var buttons = null;
            if (buttonSettings.custom.length != 0) {
                buttons = baseButtons.concat(buttonSettings.custom);
            } else {
                buttons = baseButtons;
            }
            $("<tr class='mrdBtnTr'><td id='mf_buttons_container'>")
                .appendTo(table);
            $("#mf_buttons_container").attr({
                "colspan": settings.numCount * 2,
                "align": buttonSettings.position
            });
            $.each(buttons, function (i, n) {
                var btnObj = $("<input>", {
                    'type': n.type == 'reset'
                        ? 'reset'
                        : 'button',
                    'id': n.id
                }).button({
                    'disabled': n.disabled,
                    'label': n.value
                }).css($.mrdForm.buttonBaseCss);
                if (n.type != 'reset') {
                    btnObj.click(n.click);
                }
                btnObj.appendTo($("#mf_buttons_container"));
            });
        },
        /**
         * 添加隐藏表单
         */
        _addHiddenControl: function (table, hiddenArray) {
            $.each(hiddenArray, function (i, n) {
                n.value = $.mrdForm.getControlValue(n.name, n.value);
                $("<input>", {
                    'name': n.name,
                    'value': n.value,
                    'type': 'hidden'
                }).appendTo(table);
            });
        },
        /**
         * 创建基本输入框
         */
        _addBaseControl: function (td, columnSettings) {
            /*******************************************************************
             * columnSettings.value = this.getControlValue(columnSettings.name,
             * columnSettings.value); var input = $("<input>", { 'name' :
			 * columnSettings.name, 'value' : columnSettings.value, 'type' :
			 * "text", 'width' : "98%"
			 * }).addClass(columnSettings.validate).appendTo(td); if
             * (columnSettings.readonly == true || columnSettings.readonly ==
             * 'true') { input.attr({ "readonly" : "readonly", "disabled" :
			 * "disabled" }); }
             ******************************************************************/
        },
        /**
         * 创建teatarea输入框
         */
        _addTextAreaControl: function (td, columnSettings) {
            columnSettings.value = this.getControlValue(columnSettings.name,
                columnSettings.value);
            var textarea = $("<textarea>", {
                'name': columnSettings.name,
                'value': columnSettings.value,
                'rows': columnSettings.rows,
                'width': "98%"
            }).addClass(columnSettings.validate).appendTo(td);
            if (columnSettings.readonly == true
                || columnSettings.readonly == 'true') {
                textarea.attr({
                    "readonly": "readonly",
                    "disabled": "disabled"
                });
            }
        },
        /**
         * 创建下拉框
         */
        _addDropdownControl: function (td, columnSettings) {
            columnSettings.value = this.getControlValue(columnSettings.name,
                columnSettings.value);
            var value_input = $("<input>", {
                'name': columnSettings.name,
                'value': columnSettings.value,
                'type': "hidden"
            });
            var dropdownLabelName = this
                .getDropDwonLabelName(columnSettings.name);
            columnSettings.dropdownValue = this.getControlValue(
                dropdownLabelName, columnSettings.dropdownValue);
            var input = $("<input>", {
                'name': dropdownLabelName,
                'value': columnSettings.dropdownValue,
                'type': "text",
                'width': "98%"
            }).addClass(columnSettings.validate);
            if (columnSettings.readonly == true
                || columnSettings.readonly == 'true') {
                input.attr({
                    "readonly": "readonly",
                    "disabled": "disabled"
                });
            }
            if (columnSettings.dropdownType == "ajax") {
                this._addAjaxDropdown(input, columnSettings);
            } else {
                this._addBaseDropdown(input, columnSettings);
            }
            this._addDropdownEvent(input, value_input, columnSettings);
            this._addDropdownData(input);
            input.on("change", function () {
                if ($.mrdForm.isEmpty(input.val()))
                    value_input.val("");
            });
            value_input.appendTo(td);
            input.appendTo(td);
        },
        /**
         * 添加多选下拉框控件
         */
        _addMunliselectControl: function (td, columnSettings) {
            this._addDropdownControl(td, columnSettings);
            var input = $(td).find("input").last();
            var value_input = $(td).find("input").first();
            this._addMunliselectEvent(input, value_input, columnSettings);
            this._addMunliselectData(input);
        },
        /**
         * 创建日期输入框
         */
        _addDateControl: function (td, columnSettings) {
            this._addBaseControl(td, columnSettings);
            var datepicker_opt = {
                dateFormat: columnSettings.format,
                showAnim: "slideDown"
            };
            td.children().last().datepicker(datepicker_opt);
        },
        /**
         * 创建基本下拉框
         */
        _addBaseDropdown: function (input, columnSettings) {
            input.autocomplete({
                'minLength': 0,
                'source': columnSettings.data
            });
            input.on("click", function () {
                $(this).autocomplete("search", "");
            });
        },
        /**
         * 创建ajax输入框
         */
        _addAjaxDropdown: function (input, columnSettings) {
            input.autocomplete({
                minLength: this.nvl(columnSettings.minLength, 0),
                source: function (request, response) {
                    var parameter = (new Function("return {\""
                        + columnSettings.keyWordName + "\":\""
                        + request.term + "\"}"))();
                    $.ajax(columnSettings.url, {
                        data: parameter,
                        dataType: columnSettings.dataType,
                        type: columnSettings.method,
                        success: function (data) {
                            response(columnSettings.success.call(
                                columnSettings, data));
                        },
                        error: function (XMLHttpRequest, textStatus,
                                         errorThrown) {
                            if (textStatus == "parsererror") {
                                var type = XMLHttpRequest
                                    .getResponseHeader("Content-Type");
                                if (this.dataType == "json"
                                    && type == "text/javascript") {
                                    eval(XMLHttpRequest.responseText);
                                }
                            }
                        }
                    });
                }
            });
            if (columnSettings.minLength == 0
                || columnSettings.minLength == '0') {
                input.on("click", function () {
                    $(this).autocomplete("search", "");
                });
            }
        },
        /**
         * 添加下拉框事件
         */
        _addDropdownEvent: function (input, value_input, columnSettings) {
            input.autocomplete({
                focus: function (event, ui) {
                    input.val(ui.item[0]);
                    return false;
                },
                select: function (event, ui) {
                    input.val(ui.item[0]);
                    value_input.val(ui.item[1]);
                    return false;
                }
            });
        },
        /**
         * 给下拉框添加数据
         */
        _addDropdownData: function (input) {
            input.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li>").data("item.autocomplete", item).append("<a>"
                    + item[0] + "</a>").appendTo(ul);
            };
        },
        /**
         * 添加多选下拉框事件
         */
        _addMunliselectEvent: function (input, value_input, columnSettings) {
            input.autocomplete({
                focus: function (event, ui) {
                    return false;
                },
                select: function (event, ui) {
                    return true;
                }
            });
        },
        /**
         * 添加多选下拉框数据
         */
        _addMunliselectData: function (input) {
            input.data("autocomplete")._renderItem = function (ul, item) {
                var checkbox = "<a><input type='checkbox' value='" + item[1]
                    + "' />" + item[0] + "</a>";
                var li = $("<li>").data("item.autocomplete", item)
                    .append(checkbox);
                return li.appendTo(ul);
            };
        },
        /**
         * 创建数据表格函数
         *
         * @argument dom 容器
         * @argument settings mrdForm的配置
         */
        _createGrid: function (dom, settings) {
            if (settings.module == 'save') {
                var tr = $("<tr>").insertBefore($("#" + $.mrdForm.formId
                    + " > table tr").last());
                var td = $("<td>", {}).appendTo(tr);
                td.attr({
                    "colspan": settings.numCount * 2
                });
                td.css("padding", "0 5px 0 5px");
                dom = td;
            }
            var gridId = settings.grid.id;
            // 验证id和字段信息是否存在，如果不存在则不再继续创建
            if (this.isEmpty(gridId)) {
                return;
            } else if (this.isEmpty(settings.grid.colModel)) {
                return;
            }
            if ($("#" + gridId).length == 0) {
                $("<table>", {
                    id: gridId
                }).appendTo(dom);
            }
            if ($(settings.grid.pager).length == 0) {
                $("<div>", {
                    id: new String(settings.grid.pager).substr(1)
                }).appendTo(dom);
            }
            var columns = settings.grid.colModel;
            $.each(columns, function (i, n) {
                if (!$.mrdForm.isEmpty(n.dropdown)) {
                    n.formatter = function (cellvalue, options,
                                            rowObject) {
                        for (var i = 0; i < n.dropdown.length; i++) {
                            if (cellvalue == n.dropdown[i][1]) {
                                return n.dropdown[i][0];
                            }
                        }
                        if (cellvalue == null) {
                            return "";
                        }
                        return cellvalue;
                    };
                }
            });
            $("#" + gridId).jqGrid(settings.grid);
        },
        _destroy: function (obj) {
            var objs = obj.children();
            $.each(objs, function (i, n) {
                $(n).remove();
            });
            this.formContainerId = null;
            this.formId = null;
            this.mrdFormSettings = {};
        },
        _build: function (dom, options) {
            var setting = $.mrdForm._initSetting(options);
            this._createMrdForm(dom, setting);
            this._createGrid(dom, setting);
        },
        /**
         * 获取下拉框显示值字段名
         */
        getDropDwonLabelName: function (dropdownName) {
            return "control_" + dropdownName.replace(/\./g, "_") + "_dropdown";
        },
        /**
         * 获取默认值
         */
        getControlValue: function (name, value) {
            try {
                var value_tmp = this.formDefaultData;
                if (name) {
                    var ns = name.split("\.");
                    for (var i = 0; i < ns.length; i++) {
                        value_tmp = value_tmp[ns[i]];
                    }
                    if (value_tmp) {
                        return value_tmp;
                    } else {
                        return value;
                    }
                }
            } catch (e) {
                return value;
            }
        },
        /**
         * 辅助函数，如果str1为空则输出str2否则输出str1
         */
        nvl: function (str1, str2) {
            if (str1) {
                return str1;
            } else {
                return str2;
            }
        },
        /**
         * 辅助函数，用于判断str是否为空,空则输出true,不为空则输出false
         */
        isEmpty: function (str) {
            if (str) {
                return false;
            } else {
                return true;
            }
        },
        /**
         * 重置grid的大小
         */
        resizeGrid: function () {
            var selector = $("#" + this.mrdFormSettings.grid.id);
            $(window).resize(function () {
                $(selector).setGridWidth(
                    $(window).width()
                    - $(selector).getGridParam('scrollOffset'),
                    true);
            });
            return $(selector);
        },
        /**
         * 通过ajax获取下拉框的值，一般用于获取常量值，如使用状态，类型等
         */
        ajaxdp: function (url) {
            var results = null;
            $.ajax({
                "url": url,
                async: false,
                "success": function (data) {
                    results = data.results;
                },
                error: function (XMLHttpRequest, textStatus,
                                 errorThrown) {
                    if (textStatus == "parsererror") {
                        var type = XMLHttpRequest
                            .getResponseHeader("Content-Type");
                        if (this.dataType == "json"
                            && type == "text/javascript") {
                            eval(XMLHttpRequest.responseText);
                        }
                    }
                }
            });
            return results;
        },
        /**
         * 从下拉框选项中根据真实值获取显示值
         */
        dropdownShowValue: function (dropdownOptions, dropdownValue) {
            var data = "";
            $.each(dropdownOptions, function (i, n) {
                if (dropdownValue == n[1]) {
                    data = n[0];
                }
            });
            return data;
        }
    });
    var methods = {
        hide: function (selector) {
            return $(selector).hide();
        },
        show: function (selector) {
            return $(selector).show();
        },
        disable: function (selector) {
            return $(selector).button('disable');
        },
        enable: function (selector) {
            return $(selector).button('enable');
        },
        resize: function () {
            return $.mrdForm.resizeGrid();
        },
        rebuild: function (options) {
            $.mrdForm._destroy($(this));
            $.mrdForm._build($(this), options);
        },
        destroy: function () {
            return $.mrdForm._destroy($(this));
        },
        formVal: function (fieldName) {
            return $("#" + $.mrdForm.formContainerId + " input[name='"
                + fieldName + "']").val();
        },
        refreshGrid: function () {
            var gridSelect = "#" + $.mrdForm.mrdFormSettings.grid.id;
            var filters = $.mrdForm.filterString();
            // 如果没有查询条件，则返回
            if (!$.mrdForm.isEmpty(filters)) {
                var postData = $(gridSelect).jqGrid("getGridParam", "postData");// 获取将要提交的数据
                $.extend(postData, {
                    filters: filters
                });// 将filters插入将要提交的数据
            }
            $(gridSelect).jqGrid("setGridParam", {
                search: true
                // 将jqGrid的search选项设为true
            }).trigger("reloadGrid", [{
                page: 1
            }]); // 重新载入Grid表格
        }
    };

    /**
     * 工具方法
     */
    function util() {
        this.getControlValue = function (name, value) {
            try {
                var value_tmp = $.mrdForm.formDefaultData;
                if (name) {
                    var ns = name.split("\.");
                    for (var i = 0; i < ns.length; i++) {
                        value_tmp = value_tmp[ns[i]];
                    }
                    if (value_tmp) {
                        return value_tmp;
                    } else {
                        return value;
                    }
                }
            } catch (e) {
                return value;
            }
        };
        /**
         * 辅助函数，如果str1为空则输出str2否则输出str1
         */
        this.nvl = function (str1, str2) {
            if (str1) {
                return str1;
            } else {
                return str2;
            }
        };
    }

    /**
     * text控件
     */
    function input(settings) {
        this.util = new util();
        this.settings = settings;
        this.init = function () {

        };
        input.prototype.getCtrol = function () {
            var columnSettings = this.settings;
            columnSettings.value = this.util.getControlValue(
                columnSettings.name, columnSettings.value);
            var control = $("<input>", {
                'name': columnSettings.name,
                'value': columnSettings.value,
                'type': "text",
                'width': "98%"
            }).addClass(columnSettings.validate);
            if (columnSettings.readonly == true
                || columnSettings.readonly == 'true') {
                control.attr({
                    "readonly": "readonly",
                    "disabled": "disabled"
                });
            }
            return control;
        };
        this.create = function (dom) {
            var control = this.getCtrol();
            control.appendTo(dom);
        };
    }

    function hiddenInput(settings) {
        this.settings = settings;
        this.init = function () {
        };
        hiddenInput.prototype.getCtrol = function () {
            var it = new input(this.settings);
            var control = it.getCtrol();
            control.attr("hidden", true);
            return control;
        };
        this.create = function (dom) {
            var control = this.getCtrol();
            control.appendTo(dom);
        };
    }

    /**
     * textarea控件
     */
    function textArea(settings) {
        this.util = new util();
        this.settings = settings;
        this.init = function () {
        };
        textArea.prototype.getCtrol = function () {
            var columnSettings = this.settings;
            columnSettings.value = this.util.getControlValue(
                columnSettings.name, columnSettings.value);
            var textarea = $("<textarea>", {
                'name': columnSettings.name,
                'value': columnSettings.value,
                'rows': columnSettings.rows,
                'width': "98%"
            }).addClass(columnSettings.validate);
            if (columnSettings.readonly == true
                || columnSettings.readonly == 'true') {
                textarea.attr({
                    "readonly": "readonly",
                    "disabled": "disabled"
                });
            }
            return textarea;
        };
        this.create = function (dom) {
            var control = this.getCtrol();
            control.appendTo(dom);
        };
    }

    function dropdown(settings) {
        var dropdownObj;
        this.valueInput = null;// 存放下拉框选择值对应的真实值的输入框
        this.showInput = null;// 存放下拉框选择值显示值的输入框
        this.util = new util();
        this.settings = settings;
        this.init = function () {
            if (this.settings.dropdownType == "ajax") {
                dropdownObj = new ajaxDropdown(this);
            } else {
                dropdownObj = new baseDropdown(this);
            }
        };
        // 添加下拉框实际值字段，一般为一个隐藏字段
        dropdown.prototype.getValueCtrol = function () {
            var hideInputSetting = {
                'name': this.settings.name,
                'value': this.settings.value,
                'type': 'hidden'
            };
            var it = new hiddenInput(hideInputSetting);
            this.valueInput = it.getCtrol();
            return this.valueInput;
        };
        // 初始化下拉框显示框名称
        dropdown.prototype.getDropdownInputName = function () {
            return "control_" + this.settings.name.replace(/\./g, "_")
                + "_dropdown";
        };
        // 将真实值转义
        dropdown.prototype.getDropdownInputValue = function () {
            return this.util.getControlValue(this.getDropdownInputName,
                this.settings.dropdownValue);
        };
        // 添加下拉框基本事件
        dropdown.prototype.addDropdownBaseEvent = function () {
            var showInput = this.showInput;
            var valueInput = this.valueInput;
            showInput.autocomplete({
                focus: function (event, ui) {
                    showInput.val(ui.item[0]);
                    return false;
                },
                select: function (event, ui) {
                    showInput.val(ui.item[0]);
                    valueInput.val(ui.item[1]);
                    return false;
                }
            });

        };
        // 为下拉框添加数据
        dropdown.prototype.addDropdownData = function () {
            this.showInput.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li>").data("item.autocomplete", item).append("<a>"
                    + item[0] + "</a>").appendTo(ul);
            };
        };
        this.create = function (dom) {
            //获取隐藏字段输入框
            var hiddenInput = this.getValueCtrol();
            hiddenInput.appendTo(dom);
            //获取显示字段输入框
            var dp = dropdownObj.getShowCtrol();
            dp.appendTo(dom);
        };
    }

    function ajaxDropdown(dropdownObj) {
        //创建ajax下拉框
        this.getShowCtrol = function () {
            var dropdownInputSetting = $.extend({}, dropdownObj.settings, {
                'name': dropdownObj.getDropdownInputName(),
                'value': dropdownObj.getDropdownInputValue()
            });
            var obj = new input(dropdownInputSetting);
            dropdownObj.showInput = obj.getCtrol();
            var dropdownInput = dropdownObj.showInput;
            dropdownInput.autocomplete({
                minLength: dropdownObj.util.nvl(dropdownInputSetting.minLength, 0),
                source: function (request, response) {
                    var parameter = (new Function("return {\""
                        + dropdownInputSetting.keyWordName + "\":\""
                        + request.term + "\"}"))();
                    $.ajax(dropdownInputSetting.url, {
                        data: parameter,
                        dataType: dropdownInputSetting.dataType,
                        type: dropdownInputSetting.method,
                        success: function (data) {
                            response(dropdownInputSetting.success.call(
                                dropdownInputSetting, data));
                        },
                        error: function (XMLHttpRequest, textStatus,
                                         errorThrown) {
                            if (textStatus == "parsererror") {
                                var type = XMLHttpRequest
                                    .getResponseHeader("Content-Type");
                                if (this.dataType == "json"
                                    && type == "text/javascript") {
                                    eval(XMLHttpRequest.responseText);
                                }
                            }
                        }
                    });
                }
            });
            if (dropdownInputSetting.minLength == 0
                || dropdownInputSetting.minLength == '0') {
                dropdownInput.on("click", function () {
                    $(this).autocomplete("search", "");
                });
            }
            dropdownObj.addDropdownBaseEvent();// 为下拉框添加时间
            dropdownObj.addDropdownData();// 为下拉框添加数据
            return dropdownInput;
        };
    }

    // 创建基本下拉框
    function baseDropdown(dropdownObj) {
        this.getShowCtrol = function () {
            var dropdownInputSetting = $.extend({}, dropdownObj.settings, {
                'name': dropdownObj.getDropdownInputName(),
                'value': dropdownObj.getDropdownInputValue()
            });
            var obj = new input(dropdownInputSetting);
            dropdownObj.showInput = obj.getCtrol();
            var dropdownInput = dropdownObj.showInput;
            dropdownInput.autocomplete({
                'minLength': 0,
                'source': dropdownObj.settings.data
            });
            dropdownInput.on("click", function () {
                $(this).autocomplete("search", "");
            });
            dropdownObj.addDropdownBaseEvent();// 为下拉框添加时间
            dropdownObj.addDropdownData();// 为下拉框添加数据
            return dropdownInput;
        };
        /***********************************************************************
         * dropdown.prototype.getCtrol = function() { var columnSettings =
		 * this.settings; columnSettings.value = this.util.getControlValue(
		 * columnSettings.name, columnSettings.value); var value_input = $("<input>", {
		 * 'name' : columnSettings.name, 'value' : columnSettings.value, 'type' :
		 * "hidden" }); var dropdownLabelName = this
		 * .getDropDwonLabelName(columnSettings.name);
		 * columnSettings.dropdownValue = this.getControlValue(
		 * dropdownLabelName, columnSettings.dropdownValue); var input = $("<input>", {
		 * 'name' : dropdownLabelName, 'value' : columnSettings.dropdownValue,
		 * 'type' : "text", 'width' : "98%"
		 * }).addClass(columnSettings.validate); if (columnSettings.readonly ==
		 * true || columnSettings.readonly == 'true') { input.attr({ "readonly" :
		 * "readonly", "disabled" : "disabled" }); } if
		 * (columnSettings.dropdownType == "ajax") {
		 * this._addAjaxDropdown(input, columnSettings); } else {
		 * this._addBaseDropdown(input, columnSettings); }
		 * this._addDropdownEvent(input, value_input, columnSettings);
		 * this._addDropdownData(input); input.on("change", function() { if
		 * ($.mrdForm.isEmpty(input.val())) value_input.val(""); });
		 * value_input.appendTo(td); };
         **********************************************************************/
    }

    /**
     * mrdForm对象，参数为方法名，获取初始化对象
     */
    $.fn.mrdForm = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(
                arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return this.each(function () {
                $.mrdForm._build($(this), method);
            });
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.tooltip');
        }
    };
}(jQuery));